package com.mjh.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;

public class GravatarUtil {

	private final static String GRAVATAR_URL = "http://www.gravatar.com/avatar/";
	private final static int SIZE = 36;
	private final static String RATING = "g";			//pg r x g  照片等级，是否涉及成人内容
	private final static String DEFAULT_IMG = "identicon";	//identicon wavatar or http://www.iplaysoft.com/plus/images/avatar.png
	
	private static String formatUrlParameters() {
		List<String> params = new ArrayList<String>();
		params.add("s=" + SIZE);
		params.add("r=" + RATING);
		params.add("d=" + DEFAULT_IMG);
		return "?" + StringUtils.join(params.iterator(), "&");
	}
	
	private static String hex(byte[] array) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < array.length; ++i) {
			sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));        
		}
		return sb.toString();
	}
	  
	private static String md5Hex (String message) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			return hex (md.digest(message.getBytes("CP1252")));
		} catch (NoSuchAlgorithmException e) {	
		} catch (UnsupportedEncodingException e) {
		}
		return "";
	}

	public static String getUrl(String email) {
		if(email==null) email = "";
		String emailHash = md5Hex(email.toLowerCase().trim());
		String params = formatUrlParameters();
		return GRAVATAR_URL + emailHash + ".jpg" + params;
	}
}
